package com.pengheng.mqtt.platform;


import cn.hutool.core.collection.CollUtil;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

/**
 * MQTT配置信息
 */
@Configuration
public class MqttConfig {

    @Resource
    private PushCallback pushCallback;

    @Resource
    private MqttProperties mqttProperties;


    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient mqttClient = new MqttClient(mqttProperties.getHostUrl(), mqttProperties.getClientId(), new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        options.setConnectionTimeout(mqttProperties.getTimeout());
        options.setKeepAliveInterval(mqttProperties.getKeepalive());
        mqttClient.setCallback(pushCallback);
        mqttClient.connect(options);
        //如果集合不为空 启动时候就订阅
        if (CollUtil.isNotEmpty(mqttProperties.getDefaultTopic())) {
            List<String> defaultTopic = mqttProperties.getDefaultTopic();
            String[] topicArr = new String[defaultTopic.size()];
            int[] qosArr = new int[defaultTopic.size()];
            for (int i = 0; i < defaultTopic.size(); i++) {
                qosArr[i] = 0;
                topicArr[i] = defaultTopic.get(i);
            }
            mqttClient.subscribe(topicArr, qosArr);
        }

        return mqttClient;
    }


}
